use serde::Deserialize;

fn default_port() -> u16 {
    6379
}

#[derive(Debug, Clone, Deserialize)]
pub struct RedisConfig {
    pub host: String,
    #[serde(default = "default_port")]
    pub port: u16,
    pub username: Option<String>,
    pub password: Option<String>,
    pub database: Option<u8>,
}

impl Default for RedisConfig {
    fn default() -> Self {
        Self {
            host: "127.0.0.1".to_owned(),
            port: default_port(),
            username: None,
            password: None,
            database: Default::default(),
        }
    }
}

impl RedisConfig {
    /// `redis://[[username:]password@]host[:port][/database]`
    pub fn url(&self) -> String {
        let host = &self.host;
        let port = self.port;
        let database = self.database.unwrap_or(0);
        let mut url = String::from("redis://");
        if let Some(username) = &self.username {
            url += username.as_str();
            url += ":";
        }
        if let Some(password) = &self.password {
            url += password.as_str();
            url += "@";
        }
        url += &format!("{host}:{port}/{database}");
        url
    }
}
